import Pool from './base/pool';

let instance;

/**
 * 全局状态管理器
 * 管理游戏中所有用到的数据
 */
export default class DataBus {
  constructor() {
    if (instance) return instance

    instance = this

    this.pool = new Pool()

    this.reset()
  }

  reset() {
    this.frame = 0
    this.score = 0
    this.gameOver = false
    
    // 五子棋相关状态
    this.currentPlayer = 1 // 1: 黑棋, 2: 白棋
    this.board = [] // 15x15的棋盘
    this.lastMove = null // 最后一步的位置
    this.winner = null // 获胜者
    this.gameStarted = false
    
    // 悔棋次数管理
    this.undoCounts = { 1: 3, 2: 3 } // 每个玩家3次悔棋机会
    this.moveHistory = [] // 记录落子历史，用于悔棋
    
    // 在线对战相关状态
    this.isOnlineMode = false
    this.isMyTurn = false
    this.myPlayer = 1 // 1=黑棋, 2=白棋
    this.opponentConnected = false
    this.roomId = null
    this.gameStarted = false
    
    // 人机对战相关状态
    this.isAIMode = false
    this.aiDifficulty = 'easy' // easy, medium, hard
    this.aiPlayer = 2 // AI默认执白棋
    
    // 初始化棋盘
    this.initBoard()
  }

  initBoard() {
    this.board = []
    for (let i = 0; i < 15; i++) {
      this.board[i] = []
      for (let j = 0; j < 15; j++) {
        this.board[i][j] = 0 // 0表示空位
      }
    }
  }

  /**
   * 检查是否获胜
   */
  checkWin(row, col, player) {
    const directions = [
      [1, 0],   // 水平
      [0, 1],   // 垂直
      [1, 1],   // 右下斜
      [1, -1]   // 右上斜
    ]

    for (let [dx, dy] of directions) {
      let count = 1
      
      // 正向检查
      for (let i = 1; i < 5; i++) {
        let newRow = row + dx * i
        let newCol = col + dy * i
        if (newRow < 0 || newRow >= 15 || newCol < 0 || newCol >= 15) break
        if (this.board[newRow][newCol] !== player) break
        count++
      }
      
      // 反向检查
      for (let i = 1; i < 5; i++) {
        let newRow = row - dx * i
        let newCol = col - dy * i
        if (newRow < 0 || newRow >= 15 || newCol < 0 || newCol >= 15) break
        if (this.board[newRow][newCol] !== player) break
        count++
      }
      
      if (count >= 5) return true
    }
    
    return false
  }

  /**
   * 检查是否平局（棋盘已满）
   */
  checkDraw() {
    for (let i = 0; i < 15; i++) {
      for (let j = 0; j < 15; j++) {
        if (this.board[i][j] === 0) {
          return false // 还有空位，不是平局
        }
      }
    }
    return true // 棋盘已满，平局
  }

  /**
   * 切换玩家
   */
  switchPlayer() {
    this.currentPlayer = this.currentPlayer === 1 ? 2 : 1
  }

  /**
   * 重置游戏
   */
  restart() {
    this.gameOver = false
    this.winner = null
    this.currentPlayer = 1
    this.lastMove = null
    this.undoCounts = { 1: 3, 2: 3 } // 重置悔棋次数
    this.initBoard()
    
    // 重置在线对战状态
    if (this.isOnlineMode) {
      this.isMyTurn = this.currentPlayer === this.myStoneColor
    }
  }

  /**
   * 获取当前玩家的悔棋次数
   */
  getUndoCount(player) {
    return this.undoCounts[player] || 0
  }

  /**
   * 使用悔棋
   */
  useUndo(player) {
    if (this.undoCounts[player] > 0) {
      this.undoCounts[player]--
      return true
    }
    return false
  }

  /**
   * 记录落子历史
   */
  recordMove(row, col, player) {
    this.moveHistory.push({ row, col, player })
    console.log(`记录落子: 玩家${player}在(${row}, ${col})`)
  }

  /**
   * 撤销最后一步
   */
  undoLastMove() {
    if (this.moveHistory.length > 0) {
      const lastMove = this.moveHistory.pop()
      this.board[lastMove.row][lastMove.col] = 0
      this.lastMove = this.moveHistory.length > 0 ? this.moveHistory[this.moveHistory.length - 1] : null
      console.log(`撤销落子: 玩家${lastMove.player}在(${lastMove.row}, ${lastMove.col})`)
      return lastMove
    }
    return null
  }

  /**
   * 在AI模式下撤销两步（玩家和AI的落子）
   */
  undoAIMoves() {
    if (!this.isAIMode || this.moveHistory.length < 2) {
      return false
    }
    
    // 撤销AI的落子
    const aiMove = this.moveHistory.pop()
    this.board[aiMove.row][aiMove.col] = 0
    
    // 撤销玩家的落子
    const playerMove = this.moveHistory.pop()
    this.board[playerMove.row][playerMove.col] = 0
    
    // 更新lastMove
    this.lastMove = this.moveHistory.length > 0 ? this.moveHistory[this.moveHistory.length - 1] : null
    
    console.log(`AI模式撤销两步: AI在(${aiMove.row}, ${aiMove.col}), 玩家在(${playerMove.row}, ${playerMove.col})`)
    return { aiMove, playerMove }
  }

  /**
   * 检查是否可以悔棋
   */
  canUndo(player) {
    return this.undoCounts[player] > 0
  }

  /**
   * 设置在线对战模式
   */
  setOnlineMode(isOnline, myPlayer = 1) {
    this.isOnlineMode = isOnline
    this.myPlayer = myPlayer
    this.opponentConnected = false
    this.gameStarted = false
    this.isMyTurn = myPlayer === 1 // 黑子先手
    
    if (isOnline) {
      console.log('设置在线模式:', { myPlayer, isMyTurn: this.isMyTurn })
    }
  }

  /**
   * 设置人机对战模式
   */
  setAIMode(isAI, difficulty = 'easy', aiPlayer = 2) {
    this.isAIMode = isAI
    this.aiDifficulty = difficulty
    this.aiPlayer = aiPlayer
    console.log(`设置AI模式: ${isAI}, 难度: ${difficulty}, AI执: ${aiPlayer === 1 ? '黑棋' : '白棋'}`)
  }

  /**
   * 设置对手连接状态
   */
  setOpponentConnected(connected) {
    this.opponentConnected = connected
    console.log(`对手连接状态: ${connected}`)
  }

  /**
   * 设置房间ID
   */
  setRoomId(roomId) {
    this.roomId = roomId
    console.log(`房间ID: ${roomId}`)
  }

  setMyTurn(isMyTurn) {
    this.isMyTurn = isMyTurn
    console.log(`我的回合: ${isMyTurn}`)
  }

  setGameStarted(started) {
    this.gameStarted = started
    console.log(`游戏开始: ${started}`)
  }

  /**
   * 检查是否可以落子（在线模式下只能在自己的回合落子）
   */
  canMakeMove() {
    // 检查是否可以落子
    if (!this.isOnlineMode) {
      return true // 离线模式总是可以落子
    }
    
    // 在线模式需要检查：
    // 1. 对手已连接
    // 2. 游戏已开始
    // 3. 是我的回合
    return this.opponentConnected && this.gameStarted && this.isMyTurn
  }

  /**
   * 设置游戏结束状态
   */
  setGameOver(winner) {
    this.gameOver = true
    this.winner = winner
    console.log(`游戏结束，获胜者: ${winner === 1 ? '黑棋' : '白棋'}`)
  }

  /**
   * 处理对手的落子
   */
  handleOpponentMove(row, col, player) {
    // 处理对手的落子
    if (this.board[row][col] !== 0) {
      console.warn('对手落子位置已有棋子')
      return false
    }
    
    this.board[row][col] = player
    this.lastMove = { row, col, player }
    
    // 检查是否获胜
    if (this.checkWin(row, col, player)) {
      this.setGameOver(player)
      return true
    }
    
    // 切换玩家
    this.switchPlayer()
    
    // 在线模式下，对手落子后轮到我的回合
    if (this.isOnlineMode) {
      this.setMyTurn(true)
    }
    
    console.log(`对手落子: (${row}, ${col}), 玩家: ${player === 1 ? '黑棋' : '白棋'}`)
    return true
  }
}
